﻿using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using Library.WebControls.SimpleSpinEdit;
using System;

namespace Library.WebControls.SimpleGridView {
	
	public class SpGvSpinColumn : SpGvBaseColumn {
		private readonly SpSpinEdit _spSpinEdit;

		public SpGvSpinColumn() {
			ContentStyle.HorizontalAlign = HorizontalAlign.Right;
			_spSpinEdit = new EditTextEdit(this);
			EditValueMode = EditValueMode.Attribute;
			FieldType = DataFieldType.Numeric;
		}
		private class EditTextEdit : SpSpinEdit {
			private readonly SpGvBaseColumn _column;
			public EditTextEdit(SpGvBaseColumn column) {
				_column = column;
			}

			public override bool Visible {
				get { return _column.Visible; }
				set {

				}
			}
		}
		[Description("")]
		[PersistenceMode(PersistenceMode.InnerProperty)]
		[MergableProperty(false)]
		[Category("Data")]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]

		public SpSpinEdit EditSpinEdit {
			get { return _spSpinEdit; }
		}
		[DefaultValue(SpSpinEditStyle.Float)]
		public SpSpinEditStyle NumberStyle {
			get { return _spSpinEdit.NumberStyle; }
			set { _spSpinEdit.NumberStyle = value; }
		}


		internal override BaseControl CreateClientEditControl() {
			return _spSpinEdit;
		}



		protected override string GetValueFromObject(object value) {
			if (value == null) return String.Empty;
			if (_spSpinEdit.NumberStyle == SpSpinEditStyle.Float) {
				try {
					var floatValue = Convert.ToDouble(value);
					return
							floatValue.ToString().Replace(
								System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator, ".");
				} catch (Exception) {
					return value.ToString();
				}

			}
			return value.ToString();
		}

		protected override object GetValuePostedFromClientOnEditMode() {
			if (String.IsNullOrEmpty(EditValuePostedFromClientOnEditMode)) return null;

			string oldDes = _spSpinEdit.NumberDecimalSeparator;
			_spSpinEdit.NumberDecimalSeparator = ".";
			object value = null;
			switch (_spSpinEdit.NumberStyle) {
				case SpSpinEditStyle.Float:
					value = _spSpinEdit.ParseFloat(EditValuePostedFromClientOnEditMode);
					break;
				case SpSpinEditStyle.Integer:
					value = _spSpinEdit.ParseInt(EditValuePostedFromClientOnEditMode);
					break;
			}

			_spSpinEdit.NumberDecimalSeparator = oldDes;
			return value;
		}

		public override GridColumnType ColumnType {
			get { return GridColumnType.SpinEdit; }
		}
	}
}
